<template>
  <div>
    <!-- 头部 -->
    <nav-header></nav-header>
    <!-- 头部 -->
    <!-- 面包屑 -->
    <nav-bread>
      <span>Goods</span>
    </nav-bread>
    <div class="accessory-result-page accessory-page">
      <div class="container">
        <div class="filter-nav">
          <span class="sortby">Sort by:</span>
          <a href="javascript:void(0)" class="default cur">Default</a>
          <a href="javascript:void(0)" class="price" @click="sort()"
            >Price {{ upOrDown }}
          </a>
          <a
            href="javascript:void(0)"
            class="filterby stopPop"
            @click="showFilter"
            >Filter by</a
          >
        </div>
        <div class="accessory-result">
          <!-- filter -->
          <div
            class="filter stopPop"
            id="filter"
            :class="{ 'filterby-show': filterBy }"
          >
            <dl class="filter-price">
              <dt>Price:</dt>
              <dd>
                <a
                  href="javascript:void(0)"
                  :class="{ cur: priceChecked === 'all' }"
                  @click="priFilter('all')"
                  >All</a
                >
              </dd>
              <dd v-for="(item, index) in priceFilter" :key="index">
                <a
                  href="javascript:void(0)"
                  :class="{ cur: priceChecked === index }"
                  @click="priFilter(index)"
                  >{{ item.startPrice }} - {{ item.endPrice }}</a
                >
              </dd>
            </dl>
          </div>

          <!-- search result accessories list -->
          <div class="accessory-list-wrap">
            <div class="accessory-list col-4">
              <ul>
                <li v-for="item in goodsLists" :key="item._id">
                  <div class="pic">
                    <a href="#"
                      ><img
                        v-lazy="require('../../static/' + item.productImage)"
                        alt=""
                    /></a>
                  </div>
                  <div class="main">
                    <div class="name">{{ item.productName }}</div>
                    <div class="price">
                      {{ item.salePrice | currency('￥') }}
                    </div>
                    <div class="btn-area">
                      <a
                        href="javascript:;"
                        class="btn btn--m"
                        @click="addCart(item.productId)"
                        >加入购物车</a
                      >
                    </div>
                  </div>
                </li>
              </ul>
              <div
                class="load-more"
                v-infinite-scroll="loadMore"
                infinite-scroll-disabled="busy"
                infinite-scroll-distance="30"
              >
                <img
                  src="../assets/loading-spinning-bubbles.svg"
                  v-show="loading"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- <el-pagination
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-size="pageSize"
        layout="prev,pager, next"
        :total="total"
        background
      >
      </el-pagination> -->
      <!-- 添加购物车成功模态框 -->
      <Model v-bind:mdShow="mdShow" v-on:close="closeMdShow">
        <p slot="message">
          <svg class="icon-status-ok">
            <use
              xmlns:xlink="http://www.w3.org/1999/xlink"
              xlink:href="#icon-status-ok"
            ></use>
          </svg>
          <span>加入购物车成功!</span>
        </p>
        <div slot="btnGroup">
          <a class="btn btn--m" href="javascript:;" @click="goOnShop"
            >继续购物</a
          >
          <router-link
            class="btn btn--m btn--red"
            href="javascript:;"
            to="/cart"
            >查看购物车</router-link
          >
        </div>
      </Model>
    </div>
    <div class="md-overlay" v-show="overLayFlag" @click="closePop"></div>
    <nav-footer></nav-footer>
  </div>
</template>
<script>
import NavHeader from './../components/NavHeader.vue'
import NavFooter from './../components/NavFooter.vue'
import NavBread from './../components/NavBread.vue'
import Model from './../components/Modal.vue'
import qs from 'qs'
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      //价格过滤数组
      priceFilter: [
        {
          startPrice: '0.00',
          endPrice: '100.00'
        },
        {
          startPrice: '100.00',
          endPrice: '500.00'
        },
        {
          startPrice: '500.00',
          endPrice: '1000.00'
        },
        {
          startPrice: '1000.00',
          endPrice: '2000.00'
        }
      ],
      //控制价格过滤的激活状态
      priceChecked: 'all',
      //控制价格过滤的显示与隐藏
      filterBy: false,
      //控制遮罩的显示与隐藏
      overLayFlag: false,
      //商品列表
      goodsLists: [],
      //控制价格的升降序
      sortFlag: true,
      //当前页
      page: 1,
      //一页显示的条数
      pageSize: 8,
      //总条数
      total: 0,
      //控制鼠标滚动
      busy: true,
      //控制加载动画的显示与隐藏
      loading: false,
      upOrDown: '↑',
      //往model子组件传递值
      mdShow: false,
      //购物车中的数量
      goodsNum: 0
    }
  },
  created() {
    //获取商品列表
    this.getGoods()
  },
  methods: {
    //点击Filter by触发
    showFilter() {
      //显示遮罩层
      this.filterBy = true
      this.overLayFlag = true
    },
    //点击遮罩层触发
    closePop() {
      //隐藏遮罩层
      this.filterBy = false
      this.overLayFlag = false
    },
    //请求商品列表
    getGoods(flag) {
      //显示加载动画
      this.loading = true
      this.$axios
        .get('/goods', {
          params: {
            sort: this.sortFlag ? 1 : -1,
            page: this.page,
            pageSize: this.pageSize,
            priceLevel: this.priceChecked
          }
        })
        .then(res => {
          console.log(res)
          if (res.status !== 200) return this.$message.error('获取商品列表失败')
          //对flag进行判断，如果flag为true证明是滚动加载分页
          if (flag) {
            //如果分页了，就要利用concat进行数据累加，这样才能将每次分页的数据都显示出来
            this.goodsLists = this.goodsLists.concat(res.data.list)
            //判断返回的数据的条数count是否为0
            console.log(res.data.count)
            if (res.data.count == 0) {
              //如果返回的条数为0了，禁用滚动加载数据
              this.busy = true
              this.loading = false
            } else {
              this.busy = false
            }
          } else {
            //如果flag为空，就是正常数据请求
            this.goodsLists = res.data.list
            this.busy = false
          }
          this.total = res.total
        })
        .catch(err => console.log(err))
    },
    //降序或者升序
    sort() {
      //降序sort为-1升序为1
      this.sortFlag = !this.sortFlag
      if (this.sortFlag) {
        this.upOrDown = '↑'
      } else {
        this.upOrDown = '↓'
      }
      //把page重新复位1
      this.page = 1
      //重新获取商品列表
      this.getGoods()
    },
    //点击价格过滤触发
    priFilter(index) {
      //让当前点击的标签处于高亮状态，并把数据传递到后台做判断
      this.priceChecked = index
      //隐藏遮罩层
      this.filterBy = false
      this.overLayFlag = false
      //让当前页面重置为1
      this.page = 1
      //重新请求商品数据
      this.getGoods()
    },

    // //监听页码的变化
    // handleCurrentChange(newPage) {
    //   this.page = newPage;
    //   this.getGoods(false);
    // },
    //鼠标滚动会调用的方法
    loadMore() {
      //先禁用滚动加载数据
      this.busy = true
      setTimeout(() => {
        //半秒后进行当前页加1
        this.page++
        //获取商品，并传true
        this.getGoods(true)
      }, 500)
    },
    //添加购物车出发
    addCart(id) {
      //获取浏览器中的cookie
      const userId = this.$cookies.get('userId')
      const userName = this.$cookies.get('userName')
      // console.log(userId);
      //判断userId
      if (userId && userName) {
        //证明用户已经登陆
        this.$axios
          .post(
            '/goods/addCart',
            qs.stringify({ productId: id, userId, userName })
          )
          .then(res => {
            //status不等于200添加购物车失败
            if (res.status !== 200) return this.$message.error(res.msg)
            this.$axios
              .get('/carts/getCarts', {
                params: {
                  userId
                }
              })
              .then(res => {
                console.log(res)
                this.goodsNum = res.data.goodsNum
                this.$store.commit('countCartNum', this.goodsNum)
              })
              .catch(err => console.log(err))
            //添加购物车成功
            //显示添加购物车成功模态框
            this.mdShow = true
            this.$message.success('添加成功,早下单,早发货哦亲!')
          })
          .catch(err => console.log(err))
      } else {
        //用户没登陆
        this.$alert('您还没有登陆哦亲！', '提示', {
          confirmButtonText: '确定',
          callback: () => {
            this.$message({
              type: 'info',
              message: `请先登陆再购物亲！`
            })
          }
        })
      }
    },
    //监听添加购物车弹框的关闭事件
    closeMdShow() {
      this.mdShow = false
    },
    //点击继续购物触发
    goOnShop() {
      //隐藏模态框
      this.mdShow = false
      this.$message.success('祝您购物愉快!!!')
    }
  },
  computed: {
    ...mapState(['countCart'])
  },
  components: {
    NavHeader,
    NavFooter,
    NavBread,
    Model
  }
}
</script>

<style scoped>
/* .el-pagination {
  text-align: center;
} */
.load-more {
  height: 100px;
  line-height: 100px;
  text-align: center;
}
</style>
